$(function () {
  //1.1获取裁剪区的DOM元素
  var $image = $("#image"); //1.2配置选项
  const options = {
    //纵横比
    aspectRatio: 1, //指定预览区域
    preview: ".img-preview",
  }; //1.3创建裁剪区域
  $image.cropper(options);
  $("#btnChooseImage").on("click", function () {
    // alert(1);
    $("#file").click();
  });
  //监听用户图片选择
  $("#file").on("change", function (file) {
    // alert(1);
    console.log(file);
    var fileList = file.target.files;
    var imgURL = URL.createObjectURL(fileList[0]);
    console.log(imgURL);
    //3 重新初始化裁剪区域
    $image.cropper("destroy").attr("src", imgURL).cropper(options);
  });
  //上传图片
  $("#btnUpload").on("click", function () {
    var base64Str = $image
      .cropper("getCroppedCanvas", {
        width: 100,
        height: 100,
      })
      .toDataURL("image/png");
    console.log(base64Str);
    $.ajax({
      url: "/my/update/avatar",
      method: "POST",
      data: { avatar: base64Str },
      success: function (res) {
        if (res.status !== 0) {
          return layer.msg(res.message);
        }
        layer.msg("更换头像成功哈！");
        window.parent.getUserInfo();
      },
    });
  });
});
